package com.henry.chatkit.conversation

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.widget.ImageView
import android.widget.RelativeLayout
import com.henry.chatkit.R
import com.henry.chatkit.glide.loadImage
import com.henry.chatkit.utils.SizeUtils
import com.henry.chatkit.weight.gatherimage.SynthesizedImageView


class ConversationIconView : RelativeLayout {

    private val iconSize: Int = SizeUtils.px2dp(50)

    private lateinit var mIconView: SynthesizedImageView

    constructor(context: Context?) : super(context) {
        initView()
    }
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initView()
    }
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
            context,
            attrs,
            defStyleAttr
    ) {
        initView()
    }

    private fun initView() {
        inflate(context, R.layout.profile_icon_view, this)
        mIconView = findViewById(R.id.profile_icon)
        mIconView.defaultImage(R.drawable.default_head)
    }

    fun setProfileImageView(iconView: ImageView) {
        mIconView = iconView as SynthesizedImageView
        val params = LayoutParams(iconSize, iconSize)
        params.addRule(CENTER_IN_PARENT)
        addView(mIconView, params)
    }

    fun setIconUrls(iconUrls: List<Any>?) {
        mIconView.displayImage(iconUrls)!!.load()
    }

    fun setConversation(conv: ConversationInfo) {

        if (conv.mode == ConversationInfo.ConversationMode.WeChat) {
            setRadius(SizeUtils.dp2px(5))
        } else if (conv.mode == ConversationInfo.ConversationMode.QQ) {
            setRadius(SizeUtils.dp2px(50))
        }

        conv.id?.let { mIconView.setImageId(it) }

        if (conv.icon != null) {
            mIconView.loadImage(conv.icon, R.drawable.avatar)
            return
        }

        setIconUrls(conv.iconUrlList)
    }

    fun setRadius(radius: Int) {
        mIconView.setRadius(radius)
    }

    fun setDefaultImageResId(resId: Int) {
        val bd = context.resources.getDrawable(resId) as BitmapDrawable
        mIconView.setImageBitmap(bd.bitmap)
    }

    fun setBitmapResId(resId: Int) {
        val bd = context.resources.getDrawable(resId) as BitmapDrawable
        val bitmap: Bitmap = com.blankj.utilcode.util.ImageUtils.toRound(bd.bitmap)
        mIconView.setImageBitmap(bitmap)
    }

}